// src/router/generateRoutes.tsx
import { type ReactNode } from 'react'
import { type RouteObject, createBrowserRouter, Navigate, type Router } from 'react-router-dom'
import type { RouteConfig } from '@/types/routes'
import RouteGuard from './RouteGuard'

// 转换路由配置为react-router需要的格式
export const generateRouteObjects = (routes: RouteConfig[]): RouteObject[] => {
  return routes.map(route => {
    const routeObj: RouteObject = {
      path: route.path,
    }

    // 处理重定向
    if (route.redirect) {
      routeObj.element = <Navigate to={route.redirect} replace />
    }
    // 处理组件
    else if (route.element) {
      // 包装路由守卫
      routeObj.element = (
        <RouteGuard route={route}>
          {route.element as ReactNode}
        </RouteGuard>
      )
    }

    // 处理子路由
    if (route.children && route.children.length > 0) {
      routeObj.children = generateRouteObjects(route.children)
    }

    return routeObj
  })
}

// 创建路由实例

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const createAppRouter = (routes: RouteConfig[]): any => {
  const routeObjects = generateRouteObjects(routes)
  return createBrowserRouter(routeObjects)
}
